package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加餐品
     * keys 幂等keys
     * @param dishDto
     * @return
     */
    @PostMapping
    public R add(@RequestBody DishDto dishDto,String keys){
        //increment value 是一个Long类型的数值   幂等性
        Long o = redisTemplate.opsForValue().increment(keys);

        if(o > 1){
            return R.error("已经在执行中");
        }

        System.out.println(dishDto);
        dishService.saveDish(dishDto);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R findByPage(Integer page,Integer pageSize,String name){

        Page<DishDto> pageInfo =  dishService.findByPage(page,pageSize,name);

        return R.success(pageInfo);
    }

    //http://localhost:8080/dish/1397849739276890114
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){
        DishDto dishDto = dishService.findDishDtoById(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping()
    public R update(@RequestBody DishDto dishDto){

        dishService.updateDishDto(dishDto);

        return R.success("修改成功");
    }

    /**
     * 根据分类查询菜品列表
     * 优化  还得返回口味列表
     */
    @GetMapping("/list")
    public R findDishsByCategoryId(Long categoryId,Integer status){
        List<DishDto> dishes = dishService.findDishsByCategoryId(categoryId,status);
        return R.success(dishes);
    }


    
}
